﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MassMailing.WPF.Commands
{
    /// <summary>
    /// Abstract base class for all Commands.
    /// </summary>
    public abstract class BaseCommand : ICommand
    {
        #region Private Fields

        /// <summary>
        /// A boolean to specify whether to execute asynchronously or 
        /// synchronously.
        /// </summary>
        private bool _asynchronously;

        #endregion

        #region Public Properties

        /// <summary>
        /// The list of exceptions that occurred when executing the command.
        /// </summary>
        public List<Exception> UnhandledExceptions { get; private set; }

        #endregion

        #region Constructors

        /// <summary>
        /// Default Constructor
        /// </summary>
        public BaseCommand()
        {
            _asynchronously = true;
            UnhandledExceptions = new List<Exception>();
        }

        #endregion

        #region Methods

        /// <summary>
        /// Executes the command for the specified class.
        /// </summary>
        /// <param name="asynchronous">
        /// Whether to perform the operation synchronously or asynchronously.
        /// </param>
        /// <returns>
        /// A task that has been executed that can optionaly be used to wait
        /// on completion of execution.
        /// </returns>
        public Task Execute(bool asynchronous)
        {
            _asynchronously = asynchronous;

            Task result;
            if (_asynchronously)
            {
                result = Task.Factory.StartNew(ThreadCall);
            }
            else
            {
                ThreadCall();
                result = new Task(ThreadCall);
            }

            return result;
        }

        /// <summary>
        /// Performs all the commands according to asynchronous settings and
        /// then waits for all the actions to complete.
        /// </summary>
        /// <param name="commands">A parameter array of commands to execute.</param>
        protected void ExecuteCommandsAndWait(params ICommand[] commands)
        {
            ExecuteCommandsAndWait(commands as IEnumerable<ICommand>);
        }

        /// <summary>
        /// Performs all the commands according to asynchronous settings and then waits
        /// for all the actions to complete.
        /// </summary>
        /// <param name="commands">A set of commands to execute.</param>
        protected void ExecuteCommandsAndWait(IEnumerable<ICommand> commands)
        {
            List<Task> tasks = new List<Task>();

            foreach (ICommand command in commands)
            {
                Task executedTask = command.Execute(_asynchronously);
                tasks.Add(executedTask);
            }

            if (_asynchronously && tasks.Any())
                Task.WaitAll(tasks.ToArray());

            //Once all commands have finished executing collect all of the exceptions.
            foreach (ICommand command in commands)
            {
                UnhandledExceptions.AddRange(command.UnhandledExceptions);
            }
        }

        /// <summary>
        /// Forces the execution of commands synchronously no matter
        /// what the asynchronous setting is set to, but still allows for grand-children commands
        /// to be executed asynchronously.
        /// </summary>
        /// <param name="commands">A parameter array of commands to execute.</param>
        protected void ExecuteCommandsSynchronously(params ICommand[] commands)
        {
            ExecuteCommandsSynchronously(commands as IEnumerable<ICommand>);
        }

        /// <summary>
        /// Forces the execution of commands synchronously no matter 
        /// what the asynchronous setting is set to, but still allows for grand-children commands
        /// to be executed asynchronously.
        /// </summary>
        /// <param name="commands">A set of commands to execute.</param>
        protected void ExecuteCommandsSynchronously(IEnumerable<ICommand> commands)
        {
            foreach (ICommand command in commands)
            {
                Task executedTask = command.Execute(_asynchronously);
                if (_asynchronously) executedTask.Wait();
                UnhandledExceptions.AddRange(command.UnhandledExceptions);
            }
        }

        /// <summary>
        /// Has to be overridden and contains the logic for the command.
        /// </summary>
        protected abstract void PerformCommand();

        /// <summary>
        /// A function that will be used to perform the command and
        /// take care of keeping track of unhandled exceptions.
        /// </summary>
        private void ThreadCall()
        {
            try
            {
                PerformCommand();
            }
            catch (Exception ex)
            {
                lock (UnhandledExceptions)
                {
                    UnhandledExceptions.Add(ex);
                }
            }
        }

        #endregion
    }
}
